package com.yzion.baselib.utils

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Outline
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.ViewOutlineProvider
import androidx.annotation.RequiresApi
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.Utils
import com.yzion.baselib.app.BaseApp
import com.yzion.baselib.app.IAppProvider
import com.yzion.baselib.http.ApiHelper
import com.yzion.baselib.http.BaseResponse
import okhttp3.MediaType
import okhttp3.Request
import okio.Buffer
import retrofit2.Response

/**
 * 通用N次点击回调
 */
inline fun View.onMultiClick(clickCount: Int, crossinline onClick: (v: View) -> Unit) {
    setOnClickListener(object : ClickUtils.OnMultiClickListener(clickCount) {

        override fun onTriggerClick(v: View) {
            onClick.invoke(v)
        }

        override fun onBeforeTriggerClick(v: View, count: Int) {
        }
    })
}

/**
 * 通用防抖单击回调
 */
inline fun View.onSingleClick(crossinline onClick: (v: View) -> Unit) {
    setOnClickListener(object : ClickUtils.OnDebouncingClickListener(false, 400) {
        override fun onDebouncingClick(v: View) {
            onClick.invoke(v)
        }
    })
}

/**
 * 默认样式的Toast，可以通过复写BaseApp中的createToastView来自定义样式，具体参见源码
 */
fun showToast(msg: String?) {
    ThreadUtils.runOnUiThread {
        try {
            val v = (Utils.getApp() as IAppProvider).createToastView(Utils.getApp())
            v.setMsgText(msg)
            ToastUtils.getDefaultMaker()
                .setGravity(Gravity.BOTTOM, 0, 0)
                .show(v.getView())
        } catch (e: Exception) {

        }
    }
}

/**
 * 设置view圆角
 *
 * @param radius
 * @return
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
fun setBannerRound(view: View, radius: Float) {
    view.outlineProvider = object : ViewOutlineProvider() {
        override fun getOutline(view: View, outline: Outline) {
            outline.setRoundRect(0, 0, view.width, view.height, radius)
        }
    }
    view.clipToOutline = true
}

/**
 * body内容输出成String
 */
fun Request.bodyToString(): String? {
    return try {
        val copy = newBuilder().build()
        val buffer = Buffer()
        copy.body!!.writeTo(buffer)
        buffer.readUtf8()
    } catch (e: Exception) {
        null
    }
}

/**
 * view转bitmap，用于截图
 *
 * @param v View
 * @return Bitmap
 */
fun viewToBitmap(v: View): Bitmap? {
    val w: Int = v.width
    val h: Int = v.height
    val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
    val c = Canvas(bmp)
    c.drawColor(Color.WHITE)
    v.draw(c)
    return bmp
}

/**
 * 判断请求是否成功，一般用于同步方法中的判断响应是否成功
 * 1.http状态成功，if the code is in [200..300), which means the request was successfully received,
 * understood, and accepted.
 * 2.服务器请求返回成功，该成功的代码是服务器自定义的，需要在HttpConfig中的configResponseSuccessCode方法中定义
 */
fun <T : BaseResponse<*>> Response<T>.isSuccess(): Boolean {
    //根据当前请求地址找到baseUrl
    val baseUrl =
        ApiHelper.get().baseUrlList.find { raw().request.url.toString().startsWith(it) }
            ?: ""
    //根据baseUrl获取HttpConfig
    val config = ApiHelper.get().getHttpConfig(baseUrl)
    if (config != null) {
        if (isSuccessful && body()?.code() == config.configResponseSuccessCode()) {
            return true
        }
    }
    return false
}

